package com.huike.business.service.impl;


import com.fasterxml.jackson.databind.util.BeanUtil;
import com.huike.business.domain.TbBusiness;
import com.huike.business.domain.vo.BusinessTrackDto;
import com.huike.business.domain.vo.BusinessTrackVo;
import com.huike.business.mapper.TbBusinessMapper;
import com.huike.business.mapper.TbBusinessTrackRecordMapper;
import com.huike.business.service.ITbBusinessTrackRecordService;
import com.huike.clues.mapper.SysDictDataMapper;
import com.huike.common.utils.DateUtils;
import com.huike.common.utils.SecurityUtils;
import com.huike.common.utils.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商机跟进记录Service业务层处理
 *
 * @author wgl
 * @date 2021-04-28
 */
@Service
public class TbBusinessTrackRecordServiceImpl implements ITbBusinessTrackRecordService {
    @Autowired
    private TbBusinessTrackRecordMapper tbBusinessTrackRecordMapper;

    @Autowired
    private TbBusinessMapper tbBusinessMapper;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    /**
     * 查询商机跟进
     *
     * @param id
     * @return
     */
    @Override
    public List<BusinessTrackVo> list(Long id) {
        List<BusinessTrackVo> list = tbBusinessTrackRecordMapper.list(id);
        if (CollectionUtils.isNotEmpty(list)) {
            for (BusinessTrackVo vo : list) {
                String keyItems = vo.getKeyItems();
                if (StringUtils.isNotEmpty(keyItems)) {
                    List<String> keys = Arrays.stream(keyItems.split(",")).map((dictLabel) -> {
                        return sysDictDataMapper.selectDictLabel("communication_point", dictLabel);
                    }).collect(Collectors.toList());
                    vo.setKeys(keys);
                }
            }
            return list;
        }
        return Collections.emptyList();
    }

    /**
     * 添加商机跟进
     *
     * @param dto
     */
    @Override
    @Transactional
    public void addRecord(BusinessTrackDto dto) {
        //修改商机表
        TbBusiness tbBusiness = new TbBusiness();
        BeanUtils.copyProperties(dto, tbBusiness);
        tbBusiness.setId(dto.getBusinessId());
        tbBusiness.setStatus("2");
        tbBusiness.setUpdateTime(DateUtils.getNowDate());
        tbBusiness.setUpdateBy(SecurityUtils.getUsername());
        tbBusinessMapper.updateTbBusiness(tbBusiness);
        //增加商务跟进记录
        dto.setCreateBy(SecurityUtils.getUsername());
        dto.setCreateTime(LocalDateTime.now());
        dto.setType("0");
        tbBusinessTrackRecordMapper.addRecord(dto);
    }
}
